// pages/address/add.js

const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            "homeflag": true,
            "name": "编辑地址"
        },

        options: {},

        uid: '',
        id: '',

        name_value: '',
        phone_value: '',
        address_value: '',
        default_value: false,


        cityTitle: '请选择',

        provinceVisible: false,
        cityVisible: false,
        regionVisible: false,
        streetVisible: false,

        // 选择器绑定值，绑定数字value
        provinceValue: [],
        cityValue: [],
        regionValue: [],
        streetValue: [],

        // input绑定值，绑定中文名
        provinceName: '',
        cityName: '',
        regionName: '',
        streetName: '',

        provinces: [],
        citys: [],
        regions: [],
        streets: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        this.setData({
            uid: App.globalData.uid || util.getAppValue('userInfo').uid,
            options
        })
        this.setData({
            id: options.id
        })

        this.get_address_detail()

    },

    // 获取省市区方法
    async getCityData(code = '') {
        let res = await request.postall(api.getcity, { code })
        if (res.code == 0) {
            let conData = res.data.con
            conData.forEach(item => {
                item.label = item.name
                item.value = item.code
            });
            return conData
        } else {
            util.showFail('地区信息获取失败')
        }
    },

    // 省份
    showprovincePicker() {
        this.setData({
            provinceVisible: true,
        });
    },

    async onPickerChange1(e) {
        // 省会改变 下级全部制空，重新请求数据
        console.log('确定');
        const { key } = e.currentTarget.dataset;
        const { value, label } = e.detail;

        console.log('picker change:', e.detail);
        this.setData({
            provinceVisible: false,
            provinceValue: value,
            provinceName: label[0],

            citys: [],
            regions: [],
            streets: [],

            cityValue: [],
            cityName: '',

            regionValue: [],
            regionName: '',

            streetValue: [],
            streetName: ''
        });

        let data = await this.getCityData(value[0])
        this.setData({
            citys: data
        })
    },

    onPickerCancel1(e) {
        const { key } = e.currentTarget.dataset;
        console.log(e, '取消');
        console.log('picker1 cancel:');
        this.setData({
            provinceVisible: false,
        });
    },

    // 城市
    showcityPicker() {
        this.setData({
            cityVisible: true,
        });
    },

    async onPickerChange2(e) {
        console.log('确定');
        const { key } = e.currentTarget.dataset;
        const { value, label } = e.detail;

        console.log('picker change:', e.detail);
        this.setData({
            cityVisible: false,
            cityValue: value,
            cityName: label[0],

            regions: [],
            streets: [],

            regionValue: [],
            regionName: '',

            streetValue: [],
            streetName: ''
        });

        let data = await this.getCityData(value[0])
        this.setData({
            regions: data
        })
    },

    onPickerCancel2(e) {
        const { key } = e.currentTarget.dataset;
        console.log(e, '取消');
        console.log('picker1 cancel:');
        this.setData({
            cityVisible: false,
        });
    },

    // 区县
    showregionPicker() {
        this.setData({
            regionVisible: true,
        });
    },

    async onPickerChange3(e) {
        console.log('确定');
        const { key } = e.currentTarget.dataset;
        const { value, label } = e.detail;
        console.log('picker change:', e.detail);
        this.setData({
            regionVisible: false,
            regionValue: value,
            regionName: label[0],

            streets: [],

            streetValue: [],
            streetName: ''
        });

        let data = await this.getCityData(value[0])
        this.setData({
            streets: data
        })
    },

    onPickerCancel3(e) {
        const { key } = e.currentTarget.dataset;
        console.log(e, '取消');
        console.log('picker1 cancel:');
        this.setData({
            regionVisible: false,
        });
    },

    // 街道
    showstreetPicker() {
        this.setData({
            streetVisible: true,
        });
    },

    onPickerChange4(e) {
        console.log('确定');
        const { key } = e.currentTarget.dataset;
        const { value, label } = e.detail;
        console.log('picker change:', e.detail);
        this.setData({
            streetVisible: false,
            streetValue: value,
            streetName: label[0],
        });
    },

    onPickerCancel4(e) {
        const { key } = e.currentTarget.dataset;
        console.log(e, '取消');
        console.log('picker1 cancel:');
        this.setData({
            streetVisible: false,
        });
    },

    async get_address_detail() {
        let params = {
            id: this.data.id
        }
        let res = await request.post(api.addressdetail, params)
        this.setData({
            name_value: res.accept_name,
            phone_value: res.mobile,

            provinceName: res.province_name,
            cityName: res.city_name,
            regionName: res.region_name,
            streetName: res.town_name,

            address_value: res.address,
            default_value: res.is_default,
        })

        // console.log(res);
        // 省份
        let provinceData = await this.getCityData()
        this.setData({
            provinces: provinceData
        })
        provinceData.forEach((item, index) => {
            let oo = res.province_name.indexOf(item.label)
            if (oo != -1) {
                this.setData({
                    provinceValue: [item.value],
                    provinceName: item.label
                })
                return
            }
        });

        // 城市
        let cityData = await this.getCityData(this.data.provinceValue[0])
        this.setData({
            citys: cityData
        })
        cityData.forEach((item, index) => {
            let oo = res.city_name.indexOf(item.label)
            if (oo != -1) {
                this.setData({
                    cityValue: [item.value],
                    cityName: item.label
                })
                return
            }
        });

        // 区县
        let regionData = await this.getCityData(this.data.cityValue[0])
        this.setData({
            regions: regionData
        })
        regionData.forEach((item, index) => {
            let oo = res.region_name.indexOf(item.label)
            if (oo != -1) {
                this.setData({
                    regionValue: [item.value],
                    regionName: item.label
                })
                return
            }
        });

        // 街道
        let streetData = await this.getCityData(this.data.regionValue[0])
        this.setData({
            streets: streetData
        })
        // console.log(res.town_name);
        // console.log(streetData);
        if (res.town_name) {
            streetData.forEach((item, index) => {
                let oo = res.town_name.indexOf(item.label)
                if (oo != -1) {
                    this.setData({
                        streetValue: [item.value],
                        streetName: item.label
                    })
                    return
                }
            });
        }

    },

    // 地址删除
    delete_address() {
        const that = this
        wx.showModal({
            title: '提示',
            content: '是否确认删除该地址',
            showCancel: true,
            confirmText: '确认',
            success(res) {
                if (res.confirm) {
                    //console.log("正在删除" )
                    util.showLoading("正在删除")
                    let params = {
                        ids: Number(that.data.id)
                    }
                    request.post(api.addressdelete, params).then(res => {
                        let pages = getCurrentPages()
                        let prev_page = pages[pages.length - 2]
                        // 用返回页面自己的 options初始化。错误写法：this.data.options
                        prev_page.onLoad(prev_page.data.options)
                        util.hideLoading()
                        util.goBack()
                    })
                } else if (res.cancel) {
                    util.showToast('已取消')
                }
            }
        })
    },

    // 切换默认
    switching(e) {
        this.setData({
            default_value: e.detail.value
        })
    },

    // 地址修改
    update_address() {
        let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        let that = this
        if (that.data.name_value == '') {
            util.showToast('请输入收货人姓名')
            return
        }
        if (!reg.test(that.data.phone_value)) {
            util.showToast('请输入正确号码')
            return
        }
        if (this.data.provinceName == '') {
            util.showToast('请选择省份信息')
            return
        }
        if (this.data.cityName == '') {
            util.showToast('请选择城市信息')
            return
        }
        if (this.data.regionName == '' && this.data.regions.length > 0) {
            util.showToast('请选择区县信息')
            return
        }
        if (that.data.address_value == '') {
            util.showToast('请输入您的详细地址')
            return
        }

        let params = {
            // 注意此处的id是地址id 不是uid
            id: that.data.id,
            name: that.data.name_value,
            mobile: that.data.phone_value,

            province: that.data.provinceValue[0],  //province area_id
            city: that.data.cityValue[0],   //city area_id
            region: that.data.regionValue[0],    //region area_id
            area: that.data.regionValue[0],    //region area_id
            town: that.data.streetValue[0],

            province_name: that.data.provinceName,
            city_name: that.data.cityName,
            region_name: that.data.regionName,
            town_name: that.data.streetName,

            address: that.data.address_value,
            is_default: that.data.default_value ? 1 : 0,

            // street_value: that.data.street_value,
        }

        request.post(api.addressupdate, params).then(res => {
            util.showToast('地址更新成功！')

            wx.navigateBack({
                delta: 1
            })
        }).catch(() => {
            util.showToast('地址更新失败，请重试')
        })
    },

    address_input(e) {
        this.setData({
            address_value: e.detail.value
        })
    },
    name_input(e) {
        this.setData({
            name_value: e.detail.value
        })
    },
    phone_input(e) {
        this.setData({
            phone_value: e.detail.value
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})